﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls.Primitives;
using Microsoft.Windows.Controls;


namespace RG.Common.WPF
{

    public class DatePickerMonth : DatePicker
    {




        protected override void OnCalendarOpened(RoutedEventArgs e)
        {
            var popup = Template.FindName(
                "PART_Popup", this) as Popup;
            if (popup != null && popup.Child is Calendar)
            {
                ((Calendar)popup.Child).DisplayMode = CalendarMode.Year;
            }

            ((Calendar)popup.Child).DisplayModeChanged += DatePickerCo_DisplayModeChanged;
        }

        

        private void DatePickerCo_DisplayModeChanged(object sender, CalendarModeChangedEventArgs e)
        {
            


            var popup = this.Template.FindName(
                "PART_Popup", this) as Popup;
            if (popup != null && popup.Child is Calendar)
            {
                var _calendar = popup.Child as Calendar;
                if (_calendar.DisplayMode == CalendarMode.Month)
                {
                    _calendar.DisplayMode = CalendarMode.Year;

                    if (IsDropDownOpen)
                    {
                        this.SelectedDate = GetSelectedMonth(_calendar.DisplayDate);
                        this.IsDropDownOpen = false;
                        ((Calendar)popup.Child).DisplayModeChanged -=DatePickerCo_DisplayModeChanged;
                    }
                }

            }
        }

        private DateTime? GetSelectedMonth(DateTime? selectedDate)
        {

            if (selectedDate == null)
            {
                selectedDate = DateTime.Now;
            }

//            int monthDifferenceStart = DateTimeHelper.CompareYearMonth(selectedDate.Value, DisplayDateRangeStart);
//            int monthDifferenceEnd = DateTimeHelper.CompareYearMonth(selectedDate.Value, DisplayDateRangeEnd);
//
//            if (monthDifferenceStart >= 0 && monthDifferenceEnd  0, "monthDifferenceEnd should be greater than 0!");
//                    _selectedMonth = DateTimeHelper.DiscardDayTime(DisplayDateRangeEnd);

            return new DateTime(selectedDate.Value.Year,selectedDate.Value.Month,1);
        }
    }
}
